import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';
import '../../../data/models/wiki_config.dart';
import '../../../utils/storage_service.dart';
import '../../../config/app_constants.dart';
import '../../main_screen/controllers/main_screen_controller.dart';

class FavoritesController extends GetxController {
  final StorageService _storageService = Get.find<StorageService>();
  
  // 响应式状态
  final RxList<WikiItem> favorites = <WikiItem>[].obs;
  final RxBool isLoading = false.obs;
  
  @override
  void onInit() {
    super.onInit();
    loadFavorites();
  }
  
  /// 加载收藏列表
  Future<void> loadFavorites() async {
    try {
      isLoading.value = true;
      final favoriteIds = _storageService.getFavorites();
      
      // 需要从主控制器获取WikiConfig来转换ID为WikiItem
      try {
        final mainController = Get.find<MainScreenController>();
        final config = mainController.wikiConfig.value;
        if (config != null) {
          final favoriteItems = config.wikis
              .where((item) => favoriteIds.contains(item.id))
              .toList();
          favorites.assignAll(favoriteItems);
        }
      } catch (e) {
        // 如果无法获取主控制器，清空收藏列表
        favorites.clear();
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '加载收藏列表失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 添加到收藏
  Future<void> addToFavorites(WikiItem item) async {
    try {
      await _storageService.addToFavorites(item.id);
      if (!favorites.any((fav) => fav.id == item.id)) {
        favorites.add(item);
      }
      Get.snackbar(
        '成功',
        AppConstants.msgFavoriteAdded,
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '添加收藏失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 从收藏中移除
  Future<void> removeFromFavorites(WikiItem item) async {
    try {
      await _storageService.removeFromFavorites(item.id);
      favorites.removeWhere((fav) => fav.id == item.id);
      Get.snackbar(
        '成功',
        AppConstants.msgFavoriteRemoved,
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '移除收藏失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 清空所有收藏
  Future<void> clearAllFavorites() async {
    try {
      await _storageService.clearFavorites();
      favorites.clear();
      Get.snackbar(
        '成功',
        AppConstants.msgFavoritesCleared,
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '清空收藏失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 检查是否已收藏
  bool isFavorite(String itemId) {
    return favorites.any((fav) => fav.id == itemId);
  }
  
  /// 切换收藏状态
  Future<void> toggleFavorite(WikiItem item) async {
    if (isFavorite(item.id)) {
      await removeFromFavorites(item);
    } else {
      await addToFavorites(item);
    }
  }
  
  /// 打开收藏的Wiki项目
  void openFavorite(WikiItem item) {
    try {
      // 获取主屏幕控制器
      final mainController = Get.find<MainScreenController>();
      
      // 添加到历史记录
      final searchResult = WikiSearchResult(
        wiki: item,
        relevance: 1.0,
        matchedFields: [],
      );
      mainController.addToHistory(searchResult);
      
      // 构建URL并导航
      final url = _buildWikiUrl(item);
      mainController.currentWikiUrl.value = url;
      
      // 返回主屏幕
      Get.back();
      
      Get.snackbar(
        '打开Wiki',
        '正在加载 ${item.name}',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '打开Wiki失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 分享收藏项目
  Future<void> shareFavorite(WikiItem item) async {
    try {
      final url = _buildWikiUrl(item);
      final shareText = '${item.name}\n${item.nameEn.isNotEmpty ? '${item.nameEn}\n' : ''}$url';
      
      await Share.share(
        shareText,
        subject: '分享Wiki: ${item.name}',
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '分享失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 构建Wiki URL
  String _buildWikiUrl(WikiItem item) {
    // 这里需要根据实际的Wiki站点结构来构建URL
    // 暂时使用一个通用的搜索URL格式
    final baseUrl = item.url.isNotEmpty ? item.url : 'https://wiki.example.com';
    
    if (item.url.isNotEmpty) {
      return item.url;
    }
    
    // 如果没有直接URL，构建搜索URL
    final searchTerm = Uri.encodeComponent(item.name);
    return '$baseUrl/wiki/Special:Search?search=$searchTerm';
  }
  
  /// 搜索收藏
  List<WikiItem> searchFavorites(String query) {
    if (query.isEmpty) {
      return favorites.toList();
    }
    
    final lowerQuery = query.toLowerCase();
    return favorites.where((item) {
      return item.name.toLowerCase().contains(lowerQuery) ||
             item.nameEn.toLowerCase().contains(lowerQuery) ||
             item.category.toLowerCase().contains(lowerQuery) ||
             item.description.toLowerCase().contains(lowerQuery);
    }).toList();
  }
  
  /// 按类别分组收藏
  Map<String, List<WikiItem>> getFavoritesByCategory() {
    final Map<String, List<WikiItem>> grouped = {};
    
    for (final item in favorites) {
      final category = item.category.isEmpty ? '其他' : item.category;
      grouped.putIfAbsent(category, () => []);
      grouped[category]!.add(item);
    }
    
    return grouped;
  }
  
  /// 获取收藏统计信息
  Map<String, int> getFavoritesStats() {
    final stats = <String, int>{};
    
    for (final item in favorites) {
      final category = item.category.isEmpty ? '其他' : item.category;
      stats[category] = (stats[category] ?? 0) + 1;
    }
    
    return stats;
  }
  
  /// 导出收藏列表
  Future<void> exportFavorites() async {
    try {
      final favoritesList = favorites.map((item) => {
        'id': item.id,
        'name': item.name,
        'nameEn': item.nameEn,
        'category': item.category,
        'description': item.description,
        'url': item.url,
        'tags': item.tags,
      }).toList();
      
      final exportData = {
        'exportTime': DateTime.now().toIso8601String(),
        'totalCount': favorites.length,
        'favorites': favoritesList,
      };
      
      // 这里可以实现具体的导出逻辑，比如保存到文件或分享
      await Share.share(
        'My Wiki Favorites Export\n\n${exportData.toString()}',
        subject: 'Wiki收藏导出',
      );
      
      Get.snackbar(
        '成功',
        '收藏列表已导出',
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '导出失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 刷新收藏列表
  Future<void> refreshFavorites() async {
    await loadFavorites();
  }
}